﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MSAS.DIP.Common;

namespace Microsoft.Reputation.Tests.FrontEndCommon
{
    public static class VariantGenerator
    {
        /// <summary>
        /// Adds a number of artifical path segments on to the given URL
        /// </summary>
        /// <param name="url">The base URL</param>
        /// <param name="numArtificialVariants">The number of artificial path variants to add on to the URL</param>
        /// <returns>The new URL with Path Variants added.</returns>
        public static string GetUrlWithVariants(string url, int numArtificialVariants)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("The url is null or empty", url);
            }

            string modifiedUrl = url.TrimEnd('/');

            for (int i = 0; i < numArtificialVariants; i++)
            {
                string randomString = Path.GetRandomFileName();
                randomString = randomString.Replace('.', '-');

                modifiedUrl = String.Format(
                    "{0}/{1}",
                    modifiedUrl,
                    randomString);
            }

            return modifiedUrl;
        }
        
        /// <summary>
        /// Adds a number of artifical path segments on to the given URL and
        /// returns a list containing the hash of each variant of the URL.
        /// </summary>
        /// <param name="url">The base URL</param>
        /// <param name="numArtificialVariants">The number of artificial path variants to add on to the URL</param>
        /// <returns>List containing the hash of each variant of the URL, in order of most specific to least specific</returns>
        public static List<byte[]> GetVariantHashes(string url, int numArtificialVariants)
        {
            string modifiedUrl = GetUrlWithVariants(url, numArtificialVariants);

            // Commenting this code out for now, as the DataBlock tests use this and generate URL's of length larger that the specified 2084 size.
            //if (modifiedUrl.Length > 2084)
            //{
            //    throw new ApplicationException(String.Format(
            //        "The URL generated with {0} additional artificial variants is too long for the MSASAPI to handle",
            //        numArtificialVariants));
            //}

            using (MsasApi msasApi = new MsasApi(modifiedUrl))
            {
                List<byte[]> hashList = new List<byte[]>(msasApi.VariantCount);

                for (int i = 0; i < msasApi.VariantCount; i++)
                {
                    UrlVariant variant = msasApi.GetVariant(i);
                    hashList.Add(variant.sha256);
                }
                return hashList;
            }
        }
    }
}
